package com.elong.businesstravel.protocol.baseresponse;

import java.io.File;
import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Environment;
import android.text.TextUtils;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.IStateListener;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.network.loopj.android.http.TextHttpResponseHandler;
import com.android.support.jhf.utils.FileUtils;

/**
 * 返回Json格式的基类
 * 
 * @author lenovo
 * 
 */
abstract public class BaseELongJsonHttpResponse extends TextHttpResponseHandler {

	public BaseELongJsonHttpResponse() {
	}

	public BaseELongJsonHttpResponse(String encoding) {
		super(encoding);
	}

	@Override
	public void onSuccess(int statusCode, Header[] headers,
			String responseString, HttpResponse response) {
		DebugLog.logI(responseString);
		
//		FileUtils.saveFile(responseString, new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/getstationlist.json"));
		
		JSONObject jsonObject = null;
		if (null == (jsonObject = checkJson(responseString))) {
			sendFailureMessage(statusCode, headers, new byte[0],
					new HttpResponseException(statusCode,
							ErrorExceptionHandler.ERR_SERVER_RETURN));
			return ;
		}
		StringBuilder errorHotelStringBuilder = new StringBuilder();
		StringBuilder errorTicketStringBuilder = new StringBuilder();
		if (!checkHotelResponse(jsonObject, errorHotelStringBuilder) 
				&& !checkTicketResponse(jsonObject, errorTicketStringBuilder)) {
			String errorString = errorHotelStringBuilder.toString();
			if(TextUtils.isEmpty(errorString)){
				errorString = errorTicketStringBuilder.toString();
			}
			sendFailureMessage(
					statusCode,
					headers,
					new byte[0],
					new HttpResponseException(statusCode, errorString));
		} else {
			try {
				onSuccess(statusCode, headers, jsonObject);
				onResponse(this);
			} catch (Throwable e) {
				e.printStackTrace();
				sendFailureMessage(statusCode, headers, new byte[0],
						new HttpResponseException(statusCode,
								ErrorExceptionHandler.ERR_SERVER_RETURN));
			}

		}
	}

	/**
	 * 判断是否是json格式
	 * 
	 * @param responseString
	 * @return null不是json格式
	 */
	private JSONObject checkJson(String responseString) {
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(responseString);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	/**
	 * 判断返回数据是否正确，酒店接口判断
	 * 
	 * @param jsonObject
	 * @param error
	 *            错误信息
	 * @return true正确，false服务器提示错误信息
	 */
	private boolean checkHotelResponse(JSONObject jsonObject,
			StringBuilder error) {
		String result = jsonObject.optString("result", null);
		String isError = jsonObject.optString("IsError", null);

		if (null == result || result.equalsIgnoreCase("false")) {
			error.append(jsonObject.optString("resultdes", ""));
			return false;
		}
		if (result.equalsIgnoreCase("sucess")) {
			return true;
		}
		return true;
	}
	
	/**
	 * 判断返回数据是否正确，火车票接口判断
	 * 
	 * @param jsonObject
	 * @param error
	 *            错误信息
	 * @return true正确，false服务器提示错误信息
	 */
	private boolean checkTicketResponse(JSONObject jsonObject,
			StringBuilder error) {
		String isError = jsonObject.optString("IsError", null);

		if (null == isError || isError.equalsIgnoreCase("true")) {
			error.append(jsonObject.optString("ErrorMessage", ""));
			return false;
		}
		if (isError.equalsIgnoreCase("") || isError.equalsIgnoreCase("false")) {
			return true;
		}
		return true;
	}

	abstract public void onSuccess(int statusCode, Header[] headers,
			JSONObject mainJsonObject) throws Throwable;

	public void onResponse(ResponseHandlerInterface responseHandlerInterface) {
	}

}
